<template>

  <div class="upload-excel">
      <el-upload
        ref="upload"
        :drag="drag"
        :auto-upload="autoUpload"
        class="upload-demo flex1"
        :multiple="multiple"
        action="#"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :before-upload="beforeUpload"
        :accept="accept"
        :http-request="UploadFile"
        :limit="limit"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :on-success="handleSuccess">
        <template v-if="!drag">
          <div class="flex1 flex">
            <div class="flex1 flex">
              <el-button slot="trigger"
                         class="flex1 flex-box"
                         size="small" type="primary">
                {{ uploadTitle }}
              </el-button>
              <el-button
                v-if="!autoUpload"
                style="margin-left: 10px;"
                size="small"
                type="success"
                @click.stop="submitUpload">
                上传到服务器
              </el-button>
            </div>
            <div v-if="showTips" slot="tip" class="el-upload__tip">只能上传{{ accept }}文件，且不超过{{ maxSize }}M</div>
          </div>
        </template>
        <template v-if="drag">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传{{ accept }}文件，且不超过{{ maxSize }}M</div>
        </template>
      </el-upload>
  </div>

</template>
<script>
export default {
  name: 'Upload', // 上传组件
  props: {
    // 弹框start
    isShow: Boolean,
    // 更新报表上传接口
    upLoadRequest: {
      type: String,
      default: ''
    },
    // 弹框end
    // 上传多文件数量
    limit: {
      type: Number,
      default: 3
    },
    // 是否上传多文件
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否启用拖拽上传
    drag: {
      type: Boolean,
      default: false
    },
    // 接受上传的文件类型
    accept: {
      type: String,
      default: '.xlsx,.xls,.doc,.docx'
    },
    // 上传名称
    uploadTitle: {
      type: String,
      default: '点击上传'
    },
    // 最大上传兆数
    maxSize: {
      type: Number,
      default: 20,
    },
    // 是否在选取文件后立即进行上传
    autoUpload: {
      type: Boolean,
      default: true
    },
    showTips: {
      type: Boolean,
      default: true
    },
    //上传路径
    uploadRequest: {
      type: String,
      default: ''
    },
    //上传附带参数
    uploadParams: {
      type: Object,
      default: ()=>{
        return {}
      }
    },
    // 是否清除默认数据
    isClearFiles: {
      type: Boolean,
      default: false
    },
    //是否有默认file-list列表
    fileListNew: {
      type: Array,
      default: ()=>{
        return []
      }
    },
    //上传服务器前检验
    submitUploadCheck: {
      type: [Number,String],
      default: ''
    },
  },
  data() {
    return {
      fileList: [],
      urlList: [],
      allowRequest: true,
    }
  },
  watch: {
    fileList: {
      handler() {
        if(this.fileListNew&&this.fileListNew.length>0){
          this.fileList = this.fileListNew
        }
        this.$emit('fileList', this.fileList)
      },
      deep: true,
      immediate: true
    },
  },
  created() {
    if(this.fileListNew&&this.fileListNew.length>0){
      this.fileList = this.fileListNew
    }
  },
  methods: {
    // 清空已上传的文件列表
    clearFiles(){
      const vm = this
      this.$refs.upload.clearFiles();
      vm.clearFileList()
      vm.getUrlList(vm.fileList, '', true)
    },
    // 上传的时候 我需要做一些什么是
    async UploadFile(file) {
      // 系统上传方法处理
      // console.log('file', file)
      let vm = this
      // console.log('vm.allowRequest', vm.allowRequest)
      if(!vm.allowRequest) return

      //上传成功之后清除历史记录
      if(!vm.autoUpload){
        this.fileList=[];
      }

      let Flag =
        this.fileList &&
        this.fileList.some(item => {
          if (file.file.name === item.name) {
            this.$message.error('文件名称重复')
            return true
          }
        })
      if (!Flag) {
        this.fileList.push(file.file)
      } else {
        this.fileList = this.fileList.slice(0, this.fileList.length)
      }
      // 处理数据
      let uploadData = new FormData();
      // FormData传参用append()
      uploadData.append('filename', file.filename);
      uploadData.append('uploadParams', JSON.stringify(vm.uploadParams));
      for (let i = 0; i < vm.fileList.length; i++) {
        uploadData.append('file', vm.fileList[i]);
        uploadData.append('maxSize', vm.maxSize);
      }
      vm.upload.uploadFile(uploadData,vm.uploadRequest).then((res)=>{
        vm.closeFullScreen(vm.openFullScreen());
        // console.log('res', res)
        const  { code, data, msg } = res
        if(code == 0){
          if(data){
            vm.urlList = vm.urlList.concat([{
              ...data,
            }])
            vm.$emit('getUrlList', vm.urlList)
          }
        } else {
          this.handleRemove(file.file)
          vm.showMessageMin({
            message: msg,
            type: 'error'
          })
        }
      })
    },
    // 获取选中列表
    getUrlList(arr, filename, clear=false){
      const vm = this
      if(!clear){
        vm.urlList = arr.filter(item=>item.filename != filename)
      } else {
        vm.urlList = []
      }
      vm.$emit('getUrlList', vm.urlList)
    },

    beforeUpload(file) {
      let vm = this
      vm.openFullScreen()
      // console.log('检查大小 格式',file)
      // 图片大小限制
      if(file.size/(1024*1024)>vm.maxSize){
        vm.closeFullScreen(vm.openFullScreen());
        vm.showMessageMin({
          message: '上传文件应小于'+vm.maxSize+'M',
          type: 'error'
        })
        vm.allowRequest = false
        vm.clearFiles();
        return;
      }
      //    上传类型判断
      const imgName = file.name;
      const idx = imgName.lastIndexOf(".");
      if (idx != -1) {
        let ext = imgName.substr(idx + 1).toUpperCase();
        ext = ext.toLowerCase();
        // console.log('includes',vm.accept.split(',').includes('.'+ext))
        // const allow = vm.accept.split(',').includes('.'+ext)
        const allow = vm.accept.replaceAll(' ','').split(',').includes('.'+ext)
        if (!allow) {
          vm.closeFullScreen(vm.openFullScreen());
          vm.showMessageMin({
            message: `只能上传${vm.accept}文件`,
            type: 'error'
          })
          vm.allowRequest = false
          vm.clearFiles();
          return;
        }
      }
      vm.allowRequest = true
    },
    // 文件移除
    handleRemove(file, fileList) {
      // console.log('文件移除')
      const vm = this
      vm.fileList = vm.fileList.filter(item => {
        return item.uid != file.uid
      })
      vm.getUrlList(vm.urlList, file.name)
    },
    handlePreview(file) {
      // console.log(file, 'handlePreview')
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    clearFileList() {
      this.fileList = []
      this.urlList = []
    },
    submitUpload() {
      const vm = this
      if(vm.autoUpload) return
      if(!vm.submitUploadCheck){
        vm.showMessageMin({
          message: `上传服务器前需要先填写版本号`,
          type: 'error'
        })
        return;
      }
      this.$refs.upload.submit();
    },
    //Element UI Upload 上传文件只能上传一次 ，再次点击上传后无反应的问题 https://blog.csdn.net/m0_48259951/article/details/122556430
    handleSuccess(res, file) {
      const vm = this
      if(vm.autoUpload) return
      if(vm.isClearFiles) {
        this.$refs.upload.clearFiles();
      }
      vm.sleep(500).then(()=>{
        vm.$emit('handleSuccess')
        if(vm.isClearFiles){
          vm.clearFiles; //上传成功之后清除历史记录
        }
      })
      // vm.$emit('handleSuccess')
    },
  }
}
</script>
<style lang="less" scoped>
::v-deep .el-upload__tip {
  margin-top: -7px !important;
  margin-right: 30px !important;
}
// 提交弹框样式
.edit-class{
  width: 100%;

  .el-select, .el-upload,
  .el-date-editor, .el-upload-dragger{
    width: 100%;
  }
}
// 弹框start
.upload-excel {
  display: flex;
  //justify-content: center;
  // margin-top: 100px;
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .btn-upload,
  .drop {
    border: 1px dashed #bbb;
    width: 350px;
    height: 160px;
    text-align: center;
    line-height: 160px;
  }
  .drop {
    line-height: 20px;
    color: #bbb;
    i {
      font-size: 60px;
      display: block;
    }
  }
}
// 弹框end
</style>
